'use client'
/**
 * @license 敏捷之道软件
 * 商业用途必须获得书面授权
 * 侵权举报: ideaswork@qq.com
 * 法律依据:《计算机软件保护条例》第二十四条
 */
import { useState, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { useToast } from "@/hooks/use-toast"
import { User } from '@/types/Model'

const PasswordForm = ({ user }: { user: User }) => {
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const { toast } = useToast()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (newPassword !== confirmPassword) {
      toast({
        variant: "destructive",
        title: "错误",
        description: "新密码和确认密码不匹配",
      })
      return
    }
    
    try {
      setIsLoading(true)
      const response = await fetch('/api/profile/password', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          currentPassword,
          newPassword
        }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || 'Failed to update password')
      }

      toast({
        title: "成功",
        description: "密码已更新",
      })
      setCurrentPassword('')
      setNewPassword('')
      setConfirmPassword('')
    } catch (error) {
      console.error('Error updating password:', error)
      toast({
        variant: "destructive",
        title: "错误",
        description: error instanceof Error ? error.message : "密码更新失败",
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Card className="mt-6">
      <CardHeader>
        <CardTitle>修改密码</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-2">
            <Label htmlFor="currentPassword">当前密码</Label>
            <Input 
              id="currentPassword" 
              type="password" 
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              required
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="newPassword">新密码</Label>
            <Input 
              id="newPassword" 
              type="password" 
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              required
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="confirmPassword">确认新密码</Label>
            <Input 
              id="confirmPassword" 
              type="password" 
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              required
            />
          </div>
          <Button type="submit" disabled={isLoading}>
            {isLoading ? '保存中...' : '保存'}
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}

export default function UserCenter() {
  const [user, setUser] = useState<User | null>(null)
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [isEditing, setIsEditing] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const { toast } = useToast()

  useEffect(() => {
    const fetchUser = async () => {
      setIsLoading(true)
      try {
        const response = await fetch('/api/profile', {
          headers: {
            'Content-Type': 'application/json',
          },
        })
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}))
          throw new Error(errorData.error || 'Failed to fetch user')
        }
        const data = await response.json()
        setUser(data)
        setEditingUser(data)
      } catch (error) {
        console.error('Error fetching user:', error)
        toast({
          variant: "destructive",
          title: "错误",
          description: error instanceof Error ? error.message : "获取用户信息失败",
        })
      } finally {
        setIsLoading(false)
      }
    }

    fetchUser()
  }, [])

  const handleSave = async () => {
    if (!editingUser) return
    
    try {
      setIsLoading(true)
      const response = await fetch('/api/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: editingUser.name,
          position: editingUser.position
        }),
      })

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        throw new Error(errorData.error || 'Failed to update user')
      }
      
      const updatedUser = await response.json()
      setUser(updatedUser)
      setEditingUser(updatedUser)
      setIsEditing(false)
      toast({
        title: "成功",
        description: "用户信息已更新",
      })
    } catch (error) {
      console.error('Error updating user:', error)
      toast({
        variant: "destructive",
        title: "错误",
        description: error instanceof Error ? error.message : "更新用户信息失败",
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="container px-8 py-8 mx-auto ">
      <h1 className="text-3xl font-bold mb-8 ">个人中心</h1>
      
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <CardTitle>个人信息</CardTitle>
            {isEditing ? (
              <div className="space-x-2">
                <Button variant="outline" onClick={() => setIsEditing(false)}>取消</Button>
                <Button onClick={handleSave} disabled={isLoading}>
                  {isLoading ? '保存中...' : '保存'}
                </Button>
              </div>
            ) : (
              <Button onClick={() => setIsEditing(true)}>编辑</Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          {user && (
            <div className="space-y-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">
                  姓名
                </Label>
                {isEditing ? (
                  <Input
                    id="name"
                    value={editingUser?.name || ''}
                    onChange={(e) => setEditingUser({ ...editingUser!, name: e.target.value })}
                    className="col-span-3"
                  />
                ) : (
                  <div className="col-span-3">{user.name}</div>
                )}
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="position" className="text-right">
                  职位
                </Label>
                {isEditing ? (
                  <Input
                    id="position"
                    value={editingUser?.position || ''}
                    onChange={(e) => setEditingUser({ ...editingUser!, position: e.target.value })}
                    className="col-span-3"
                  />
                ) : (
                  <div className="col-span-3">{user.position}</div>
                )}
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="email" className="text-right">
                  邮箱
                </Label>
                <div className="col-span-3">{user.email}</div>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="role" className="text-right">
                  角色
                </Label>
                <div className="col-span-3">{user.role}</div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {user && <PasswordForm user={user} />}
    </div>
  )
}